package rpc.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc.netty.tcp.entity.RpcMessage;
import rpc.serialize.SerializeUtils;

public class RpcMessageDecoder extends LengthFieldBasedFrameDecoder {

  private static final Logger logger = LoggerFactory.getLogger(RpcMessageDecoder.class);

  public RpcMessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength,
      int lengthAdjustment, int initialBytesToStrip) {
    super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment,
        initialBytesToStrip);
  }

  @Override
  protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
//    ByteBuf in = (ByteBuf) msg;
//    logger.info("decode  begin {}", in);
    in.markReaderIndex();
    byte flag = in.readByte();
    if (!Objects.equals(RpcMessage.getFlag(), flag)) {
      //in.resetReaderIndex();
      return null;
    }

    int length = in.readInt();
    if (in.readableBytes() < length) {
      in.resetReaderIndex();
      return null;
//      throw new RuntimeException("11133333333333");
    }
    byte[] msgBytes = new byte[length];
    in.readBytes(msgBytes);

    return SerializeUtils.deSerialize(msgBytes, RpcMessage.class);
  }
}

